"""
获取name，mac，nic_name shell脚本：
count=0
for i in `ip link show | awk '{print $2}'`
do
    let res=${count}%2
    if [[ $res -eq 0 ]]
    then
        echo "&"
        nic=`echo $i | sed 's/://'`
        speed=`ethtool $nic | grep Speed`
        echo $speed
    fi
echo "${i}"
let count+=1
done

"""
import os,re
from modules import base
class Nic(base.Base):
    def __init__(self,host_dict=None):
        self.command="""count=0;for i in `ip link show | awk '{print $2}'`;do let res=${count}%2;if [[ $res -eq 0 ]];then echo "&";nic=`echo $i | sed 's/://'`;speed=`ethtool $nic | grep Speed`;echo $speed;fi;echo "${i}";let count+=1;done"""
        self.host_dict=host_dict
        self.res_list=[]
        super(Nic,self).__init__()

    def windows(self):
        res=os.popen('wmic nic get Name,MACAddress,AdapterType,Speed').read().splitlines()
        for i in range(2):
            del res[i]
        while '' in res:
            res.remove('')
        for i in res:
            if '以太网' in i:
                if re.search('(VMware)|(Tap)|(Vir)',i): #过滤指定虚拟网卡
                    continue
                tmp_dict={}
                field=i.split('  ')
                while '' in field:
                    field.remove('')
                mac_addr=field[1]
                name=field[2]
                speed='%sMbps'%str(int(field[3])/1000/1000)
                tmp_dict['name']=name
                tmp_dict['speed']=speed
                tmp_dict['mac_addr']=mac_addr
                self.res_list.append(tmp_dict)
        base.data_dict['nic_info']=self.res_list
    def linux(self):
        if self.host_dict==None: #如果=None,则证明是agent模式
            res=os.popen(self.command).read()
            self.parse(res)
            base.data_dict['nic_info']=self.res_list

        else: #传入了host_dict，证明是ssh模式
            res=self.ssh(self.host_dict,self.command).decode(encoding='utf-8')
            self.parse(res)
            base.data_dict[self.host_dict['hostname']]['nic_info']=self.res_list
    def parse(self,data):
        new_data=data.split('&')
        for i in new_data:
            clean=i.strip('\'').replace('\n','').replace('\t','')
            if re.match('Speed',clean):
                tmp_dict={}
                speed=re.search('Speed.*Mb',clean)
                tmp_dict['speed']=speed.group().split(':')[1].strip()
                name=re.search('/s.*?:',clean).group().strip('/s').strip(':')
                if re.search('(bond)|(vir)|(vnet)|(qv)|(qb)|(tap)',name):#忽略虚拟网卡
                    continue
                tmp_dict['name']=name
                mac_addr=clean.split(':',2)[2]
                tmp_dict['mac_addr']=mac_addr
                self.res_list.append(tmp_dict)
